#!/bin/bash
## A script to handle opening urls from weechat in tmux, possibly on host maching
## Inspired by https://toxicfrog.github.io/remote-url-handling-in-weechat-and-tmux/
##
## This script is relying on the laptop opening a reverse ssh tunnel to the server
##
## Add binding for M-o #, for 1 through 9 (10 can be 0)
## /key bind meta-o1 /url_hint_replace /exec -bg weechat-open-url {url1}
## /key bind meta-o2 /url_hint_replace /exec -bg weechat-open-url {url2}
##
## You can chose between a split (split-window -h) or new (new-window) in tmux

## Reverse SSH Tunnel Check
#laptop_status="$(nc -z localhost 2001 && echo 1 || echo 0)"
## VPN Check, nc faster than a ping
laptop_status="$(nc -z -w 1 10.0.10.3 22 && echo 1 || echo 0)"
laptop_host="wgdoom"

function open-image {
    if [ ${laptop_status} == 1 ]; then
        ssh ${laptop_host} env DISPLAY=:0 feh -x -F --auto-zoom "'$1'"
  else
        tmux new-window -c ~ bash -c "timg $1 && read -s -n 1 -p 'Press Any Key to Exit'"
    fi
}

function open-url {
    if [ ${laptop_status} == 1 ]; then
        ssh ${laptop_host} env DISPLAY=:0 'XDG_RUNTIME_DIR=/run/user/$(id -u)' /usr/share/qutebrowser/scripts/open_url_in_instance.sh "'$1'"
  else
        tmux new-window -c ~ bash -c "w3m '$1'"
    fi
}

function open-video {
    ## Only exec if laptop connected
    if [ ${laptop_status} == 1 ]; then
        ssh ${laptop_host} env DISPLAY=:0 'XDG_RUNTIME_DIR=/run/user/$(id -u)' mpv --profile=rem "'$1'"
    fi
}

function open-sound {
    ## Only exec if laptop connected
    if [ ${laptop_status} == 1 ]; then
        ssh ${laptop_host} env DISPLAY=:0 'XDG_RUNTIME_DIR=/run/user/$(id -u)' mpv --profile=pod "'$1'"
    fi
}

case $(echo "$1" | tr A-Z a-z) in
    *.jpg|*.jpeg|*.png|*.gif|*.svg|*:large)
        open-image "$1"
        ;;
    *youtube.com/*|*youtu.be/*|*.gifv|*.mp4|*.webm)
        open-video "$1"
        ;;
    *.mp3)
        open-sound "$1"
        ;;
    *)
        open-url "$1"
        ;;
esac
